<template>
  <div>
    <Tabs>
      <TabPane label="代申请">
        <div style="margin-left: 15%">
          <Steps :current="step.current">
            <Step content="选择支付渠道"></Step>
            <Step content="填写申请资料"></Step>
            <Step content="提交申请资料"></Step>
            <Step content="结果反馈"></Step>
          </Steps>
        </div>
        <div class="step-content">
          <!-- 1.选择支付渠道 -->
          <div class="choose-channel" v-if="step.current === 0">
            <div class="type_tab" style="margin: 0 auto">
              <Menu ref="typeMenu" mode="horizontal" :active-name="chooseType" @on-select="selectType">
                <div class="layout-assistant">
                  <MenuItem v-for="item in channels" :name="item.type">{{item.desc}}
                  </MenuItem>
                </div>
              </Menu>
            </div>
            <div class="type_content">
              <CheckboxGroup v-model="channelChooseArr">
                <div v-for="item in channels">
                  <div v-if="item.type === chooseType">
                    <Checkbox style="width: 30%" size="large" v-for="itemInner in item.content"
                              :label="itemInner.channelCode" :key="itemInner.channelCode">
                      <span>{{itemInner.desc}}</span>
                    </Checkbox>
                  </div>
                </div>
              </CheckboxGroup>
            </div>
          </div>
          <!-- 2.填写申请资料-->
          <div class="apply-info" v-if="step.current === 1">
            <!-- 基本信息 -->
            <Tabs>
              <TabPane label="基本信息">
                <Form ref="baseInfo" :model="baseInfo" :rules="baseInfoRuleValidate" :label-width="160">
                  <FormItem label="公司名称" prop="companyName">
                    <Input v-model="baseInfo.companyName" placeholder="请填写您的公司名称"></Input>
                  </FormItem>
                  <FormItem label="企业证照" prop="companyCertificate" required>
                    <MyUploader :imgSrc="baseInfo.companyCertificate[0]" name="营业执照" :ref="refArr[0]"></MyUploader>
                    <MyUploader :imgSrc="baseInfo.companyCertificate[1]" name="组织机构代码证" :ref="refArr[1]"></MyUploader>
                    <MyUploader :imgSrc="baseInfo.companyCertificate[2]" name="税务登记证" :ref="refArr[2]"></MyUploader>
                    <MyUploader :imgSrc="baseInfo.companyCertificate[3]" name="银行开户许可证" :ref="refArr[3]"></MyUploader>
                    <MyUploader :imgSrc="baseInfo.companyCertificate[4]" name="彩色法人身份证正面" :ref="refArr[4]"></MyUploader>
                    <MyUploader :imgSrc="baseInfo.companyCertificate[5]" name="彩色法人身份证反面" :ref="refArr[5]"></MyUploader>
                  </FormItem>
                  <FormItem label="商户类别" prop="merchantType">
                    <Input v-model="baseInfo.merchantType" placeholder="请您描述APP的类别，例如游戏、电商"></Input>
                  </FormItem>
                  <FormItem label="支付申请邮箱" prop="applyEmail">
                    <Input v-model="baseInfo.applyEmail" placeholder="请填写邮箱帐号"></Input>
                  </FormItem>
                  <FormItem label="ICP备案号" prop="icpId">
                    <Input v-model="baseInfo.icpId" placeholder="如未申请，请填无"></Input>
                  </FormItem>
                  <FormItem label="ICP备案域名" prop="icpWebAddr">
                    <Input v-model="baseInfo.icpWebAddr" placeholder="如未申请，请填无"></Input>
                  </FormItem>
                  <FormItem>
                    <Button @click="handleSubmit('baseInfo')">保存</Button>
                  </FormItem>
                </Form>
              </TabPane>
            </Tabs>
            <!-- APP信息 -->
            <Tabs v-if="apps.appShow">
              <TabPane label="APP信息">
                <Form ref="appInfo" :model="appInfo" :rules="appInfoRuleValidate" :label-width="160">
                  <FormItem label="APP名称" prop="appName">
                    <Input v-model="appInfo.appName" placeholder="请填写APP名称"></Input>
                  </FormItem>
                  <FormItem label="支付场景及APP行业描述" prop="appIndustryDesc">
                    <Input v-model="appInfo.appIndustryDesc" type="textarea"
                           placeholder="用于描述APP所使用的支付场景以及用于申请支付通道的行业类型，200字以内"></Input>
                  </FormItem>
                  <FormItem label="相关行业资质" prop="industryCredit" required>
                    <MyUploader :imgSrc="appInfo.industryCredit" name="相关资质（或营业执照）"
                                ref="industryCredit"></MyUploader>
                  </FormItem>
                  <FormItem label="APP截图" prop="appScreenshot" required>
                    <MyUploader :imgSrc="appInfo.appScreenshot[0]" name="APP图标（不小于108*108px）"
                                :ref="appRefArr[0]"></MyUploader>
                    <MyUploader :imgSrc="appInfo.appScreenshot[1]" name="APP首页截图（打开APP后首先显示的页面）"
                                :ref="appRefArr[1]"></MyUploader>
                    <MyUploader :imgSrc="appInfo.appScreenshot[2]" name="APP尾页截图（必须是对应的签约公司名称）"
                                :ref="appRefArr[2]"></MyUploader>
                    <MyUploader :imgSrc="appInfo.appScreenshot[3]" name="APP商品列表（包括页面各个类目商品展示）"
                                :ref="appRefArr[3]"></MyUploader>
                    <MyUploader :imgSrc="appInfo.appScreenshot[4]" name="APP商品详情截图（产品详情页面）"
                                :ref="appRefArr[4]"></MyUploader>
                    <MyUploader :imgSrc="appInfo.appScreenshot[5]" name="APP支付页（需展示APP内拟放置的支付通道页面）"
                                :ref="appRefArr[5]"></MyUploader>
                  </FormItem>
                  <FormItem label="APP平台" prop="appPlatform">
                    <CheckboxGroup v-model="appInfo.appPlatform" @on-change="chooseApps">
                      <Checkbox label="ANDROID">
                        <Icon type="social-android"></Icon>
                        <span>安卓</span>
                      </Checkbox>
                      <Checkbox label="IOS">
                        <Icon type="social-apple"></Icon>
                        <span>苹果</span>
                      </Checkbox>
                    </CheckboxGroup>
                  </FormItem>
                  <FormItem label="IOS Bundle ID 应用包名" prop="bundleId" v-if="apps.iosShow">
                    <Input v-model="appInfo.bundleId" placeholder="IOS应用上唯一标识"></Input>
                  </FormItem>
                  <div v-if="apps.androidShow">
                    <FormItem label="Android 应用包名" prop="packageName">
                      <Input v-model="appInfo.packageName" placeholder="应用在一台设备上的唯一标识"></Input>
                    </FormItem>
                    <FormItem label="Android 应用签名" prop="appSignature">
                      <Input v-model="appInfo.appSignature" placeholder="由开发者签名改应用签名的keystore文件决定"></Input>
                    </FormItem>
                  </div>
                  <FormItem>
                    <Button @click="handleSubmit('appInfo')">保存</Button>
                  </FormItem>
                </Form>
              </TabPane>
            </Tabs>
            <!-- 支付联系人信息 -->
            <Tabs>
              <TabPane label="支付联系人信息">
                <Form ref="payContactInfo" :model="payContactInfo" :rules="payContactInfoRuleValidate"
                      :label-width="160">
                  <FormItem label="联系人姓名" prop="contactName">
                    <Input v-model="payContactInfo.contactName" placeholder="请输入联系人姓名"></Input>
                  </FormItem>
                  <FormItem label="联系人手机" prop="contactTel">
                    <Input v-model="payContactInfo.contactTel" placeholder="请输入联系人手机号码"></Input>
                  </FormItem>
                  <FormItem label="联系人邮箱" prop="contactEmail">
                    <Input v-model="payContactInfo.contactEmail" placeholder="请输入联系人邮箱帐号"></Input>
                  </FormItem>
                  <FormItem>
                    <Button @click="handleSubmit('payContactInfo')">保存</Button>
                  </FormItem>
                </Form>
              </TabPane>
            </Tabs>
          </div>
          <!-- 3.提交申请资料 -->
          <div class="submit-info" v-if="step.current === 2">
            <p>您的的申请材料已提交，我们会在第一时间邮件和电话通知您申请结果，请及时查收。
              您正在申请的支付产品有
            </p>
            <div class="item-info" v-for="item in channelChooseArr">
              {{item}}
            </div>
          </div>
          <!-- 4.结果反馈-->
          <div class="result-back" v-if="step.current === 3">
            结果反馈
          </div>
          <div class="button-group">
            <Button @click="preStep" v-if="step.current == 1">上一步</Button>
            &nbsp;&nbsp;&nbsp;
            <Button @click="nextStep" v-if="step.current == 0">下一步</Button>
            <Button @click="handleSubmit('all')" v-if="step.current == 1">提交</Button>
            <Button @click="nextStep" v-if="step.current == 2">确认</Button>
          </div>
        </div>
      </TabPane>
    </Tabs>
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import Model from '@/models/apps'
  import MyUploader from '@/components/MyUploader'
  export default {
    name: 'agency',
    components: {
      'MyUploader': MyUploader
    },
    data (){
      const validateTel = (rule, value, callback) => {
        if (!(/^1[34578]\d{9}$/.test(value))) {
          callback(new Error('手机号码格式不正确'))
        } else {
          callback()
        }
      }
      return {
        refArr: ['license', 'organization', 'invoice', 'bank', 'front', 'back'],
        appRefArr: ['appIcon', 'appIndex', 'appLast', 'appProdList', 'appProdDetail', 'appPayPage'],
        imgName: '',
        visible: false,
        uploadList: [],
        step: {
          current: 0
        },
        baseInfo: {
          companyName: '',
          companyCertificate: [],
          merchantType: '',
          applyEmail: '',
          icpId: '',
          icpWebAddr: ''
        },
        baseInfoRuleValidate: {
          companyName: [
            {required: true, message: '公司名称不能为空', trigger: 'blur'}
          ],
          merchantType: [
            {required: true, message: '商户类别不能为空', trigger: 'blur'}
          ],
          applyEmail: [
            {required: true, message: '支付申请邮箱不能为空', trigger: 'blur'},
            {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
          ],
          icpId: [
            {required: true, message: 'ICP备案号不能为空', trigger: 'blur'}
          ],
          icpWebAddr: [
            {required: true, message: 'ICP备案域名不能为空', trigger: 'blur'}
          ]
        },
        appInfo: {
          appName: '',
          appIndustryDesc: '',
          industryCredit: '',
          appPlatform: [],
          appScreenshot: [],
          bundleId: '',
          packageName: '',
          appSignature: ''
        },
        appInfoRuleValidate: {
          appName: [
            {required: true, message: '产品名称不能为空！', trigger: 'blur'}
          ],
          appIndustryDesc: [
            {required: true, message: '行业描述不能为空！', trigger: 'blur'}
          ],
          appPlatform: [
            {required: true, type: 'array', min: 1, message: '至少选择一个APP平台！', trigger: 'change'}
          ],
          bundleId: [
            {required: true, message: 'IOS Bundle ID 应用包名不能为空！', trigger: 'blur'}
          ],
          packageName: [
            {required: true, message: 'ICP备案号不能为空！', trigger: 'blur'}
          ],
          appSignature: [
            {required: true, message: 'ICP备案域名不能为空！', trigger: 'blur'}
          ]
        },
        payContactInfo: {
          contactName: '',
          contactTel: '',
          contactEmail: ''
        },
        payContactInfoRuleValidate: {
          contactName: [
            {required: true, message: '联系人姓名不能为空！', trigger: 'blur'}
          ],
          contactTel: [
            {required: true, message: '联系人手机不能为空！', trigger: 'blur'},
            {validator: validateTel, trigger: 'blur'}
          ],
          contactEmail: [
            {required: true, message: '联系人邮箱不能为空！', trigger: 'blur'},
            {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
          ]
        },
        channels: [],
        chooseType: '',
        channelChooseArr: [],
        apps: {
          appShow: false,
          androidShow: false,
          iosShow: false
        }
      }
    },
    computed: mapState({
      'allApps': state => state.allApps,
      getCurrentApp (state) {
        return state.allApps.currentApp
      }
    }),
    watch: {
      getCurrentApp (val) {
        this.getApplyInfo()
      }
    },
    created () {
      this.init()
      this.selectType(this.channels[0].type)
    },
    methods: {
      init () {
        this.listChannels()
        this.getApplyInfo()
      },
      selectType (name) {
        this.chooseType = name
      },
      preStep () {
        this.getApplyInfo()
        this.step.current = this.step.current - 1
      },
      nextStep () {
        if (this.step.current === 0) {
          if (this.channelChooseArr.length === 0) {
            this.$Message.error('至少选择一个渠道！！！')
            return
          }
          this.saveChannels()
          // 选择APP类型的渠道，需要填写APP信息
          if (this.contains(this.channelChooseArr, 'APP', true)) {
            this.apps.appShow = true
          } else {
            this.apps.appShow = false
          }
        }
        this.step.current = this.step.current + 1
      },
      chooseApps (value) {
        this.apps.androidShow = this.contains(value, 'ANDROID')
        this.apps.iosShow = this.contains(value, 'IOS')
      },
      listChannels () {
        new Model('listChannels')
          .GET()
          .then((res) => {
            this.channels = res.data
            this.chooseType = this.channels[0].type.toString()
            this.$nextTick(() => {
              this.$refs.typeMenu.updateActiveName()
            })
          })
      },
      getApplyInfo () {
        new Model('applyInfo')
          .GET({
            params: {
              productId: this.allApps.currentApp
            }
          })
          .then((res) => {
            var data = res.data.data
            var status = data.status
            if (status === 'CREATING') {
              this.step.current = 0
            } else if (status === 'AUDITING') {
              this.step.current = 3
            }
            if (data !== null) {
              // baseInfo
              if (data.channels.indexOf(',') !== -1) {
                this.channelChooseArr = data.channels.split(',')
              } else {
                this.channelChooseArr.push(data.channels)
              }
              this.baseInfo.companyName = data.companyName
              if (data.companyCertificate.indexOf(',') !== -1) {
                this.baseInfo.companyCertificate = data.companyCertificate.split(',')
              } else {
                this.baseInfo.companyCertificate = []
              }
              this.baseInfo.merchantType = data.merchantType
              this.baseInfo.applyEmail = data.applyEmail
              this.baseInfo.icpId = data.icpId
              this.baseInfo.icpWebAddr = data.icpWebAddr
              // appInfo
              this.appInfo.industryCredit = data.industryCredit
              if (data.appScreenshot.indexOf(',') !== -1) {
                this.appInfo.appScreenshot = data.appScreenshot.split(',')
              } else {
                this.appInfo.appScreenshot = []
              }
              this.appInfo.appName = data.appName
              this.appInfo.appIndustryDesc = data.appIndustryDesc
              if (data.appPlatform !== '') {
                this.appInfo.appPlatform = data.appPlatform.split(',')
              }
              this.appInfo.bundleId = data.bundleId
              this.appInfo.packageName = data.packageName
              this.appInfo.appSignature = data.appSignature
              this.chooseApps(this.appInfo.appPlatform)
              // payContactInfo
              this.payContactInfo.contactName = data.contactName
              this.payContactInfo.contactTel = data.contactTel
              this.payContactInfo.contactEmail = data.contactEmail
            }
          })
      },
      saveChannels () {
        // 提交申请渠道记录
        new Model('applyInfo')
          .POST({
            params: {
              id: this.id,
              channels: this.channelChooseArr,
              productId: this.allApps.currentApp
            }
          })
      },
      saveBaseInfo () {
        if (!this.validateCertificate()) {
          this.$Message.error('企业证照未填写齐全！！！')
          return
        }
        this.baseInfoImg()
        new Model('applyInfo')
          .POST({
            params: {
              productId: this.allApps.currentApp,
              ...this.baseInfo
            }
          })
          .then((res) => {
            if (res.data.errorCode === '200') {
              this.$Message.success('保存成功!')
            } else {
              this.$Message.error('未知异常,保存失败!')
            }
          })
      },
      saveAppInfo () {
        var appInfoValid
        this.$refs['appInfo'].validate((valid) => {
          appInfoValid = valid
        })
        if (!appInfoValid) {
          this.$Message.error('APP信息填写不完整')
          return
        }
        if (!this.validateApp()) {
          this.$Message.error('APP信息截图上传不完整！！！')
          return
        }
        this.appInfoImg()
        new Model('applyInfo')
          .POST({
            params: {
              productId: this.allApps.currentApp,
              ...this.appInfo
            }
          })
          .then((res) => {
            if (res.data.errorCode === '200') {
              this.$Message.success('保存成功!')
            } else {
              this.$Message.error('未知异常,保存失败!')
            }
          })
      },
      savePayContactInfo () {
        new Model('applyInfo')
          .POST({
            params: {
              productId: this.allApps.currentApp,
              ...this.payContactInfo
            }
          })
          .then((res) => {
            if (res.data.errorCode === '200') {
              this.$Message.success('保存成功!')
            } else {
              this.$Message.error('未知异常,保存失败!')
            }
          })
      },
      saveAllInfo () {
        this.baseInfoImg()
        if (this.apps.appShow) {
          this.appInfoImg()
        }
        new Model('applyInfo')
          .POST({
            params: {
              productId: this.allApps.currentApp,
              status: 'AUDITING',
              ...this.appInfo,
              ...this.baseInfo,
              ...this.payContactInfo
            }
          })
          .then((res) => {
            if (res.data.errorCode === '200') {
              this.nextStep()
            } else {
              this.$Message.error('未知异常,保存失败!')
            }
          })
      },
      handleSubmit (name) {
        if (name === 'appInfo') {
          this.saveAppInfo()
        } else if (name === 'baseInfo') {
          this.saveBaseInfo()
        } else if (name === 'payContactInfo') {
          this.savePayContactInfo()
        } else if (name === 'all') {
          var appInfoValid = true
          var baseInfoValid = true
          var payContactInfoValid = true
          if (this.apps.appShow) {
            this.$refs['appInfo'].validate((valid) => {
              appInfoValid = valid
            })
          }
          this.$refs['baseInfo'].validate((valid) => {
            baseInfoValid = valid
          })
          this.$refs['payContactInfo'].validate((valid) => {
            payContactInfoValid = valid
          })
          var valid = appInfoValid && baseInfoValid && payContactInfoValid
          if (!valid) {
            this.$Message.error('信息填写不完整！！！')
            return
          }
          // 验证所有照片是否上传
          if (!this.validateCertificate()) {
            this.$Message.error('企业证照未填写齐全！！！')
            return
          }
          if (this.apps.appShow) {
            if (!this.validateApp()) {
              this.$Message.error('APP信息截图上传不完整！！！')
              return
            }
          }
          this.saveAllInfo()
        }
      },
      contains (arr, obj, type) {
        var i = arr.length
        while (i--) {
          var ele = arr[i]
          if (type) {
            ele = ele.substring(ele.indexOf('_') + 1, ele.lastIndexOf('_'))
          }
          if (ele === obj) {
            return true
          }
        }
        return false
      },
      validateCertificate () {
        return this.$refs.license.isUpload() &&
          this.$refs.organization.isUpload() &&
          this.$refs.invoice.isUpload() &&
          this.$refs.bank.isUpload() &&
          this.$refs.front.isUpload() &&
          this.$refs.back.isUpload()
      },
      validateApp () {
        return this.$refs.appIcon.isUpload() &&
          this.$refs.appIndex.isUpload() &&
          this.$refs.appLast.isUpload() &&
          this.$refs.appProdList.isUpload() &&
          this.$refs.appProdDetail.isUpload() &&
          this.$refs.appPayPage.isUpload() &&
          this.$refs.industryCredit.isUpload()
      },
      baseInfoImg () {
        this.baseInfo.companyCertificate[0] = this.$refs.license.imgSrc
        this.baseInfo.companyCertificate[1] = this.$refs.organization.imgSrc
        this.baseInfo.companyCertificate[2] = this.$refs.invoice.imgSrc
        this.baseInfo.companyCertificate[3] = this.$refs.bank.imgSrc
        this.baseInfo.companyCertificate[4] = this.$refs.front.imgSrc
        this.baseInfo.companyCertificate[5] = this.$refs.back.imgSrc
      },
      appInfoImg () {
        this.appInfo.industryCredit = this.$refs.industryCredit.imgSrc
        this.appInfo.appScreenshot[0] = this.$refs.appIcon.imgSrc
        this.appInfo.appScreenshot[1] = this.$refs.appIndex.imgSrc
        this.appInfo.appScreenshot[2] = this.$refs.appLast.imgSrc
        this.appInfo.appScreenshot[3] = this.$refs.appProdList.imgSrc
        this.appInfo.appScreenshot[4] = this.$refs.appProdDetail.imgSrc
        this.appInfo.appScreenshot[5] = this.$refs.appPayPage.imgSrc
      }
    }
  }
</script>

<style scoped src="./styles/index.css">
</style>
